package com.itrip.itripauth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itrip.common.util.MD5;
import com.itrip.itripauth.entity.HotelOrder;
import com.itrip.itripauth.entity.HotelTempStore;
import com.itrip.itripauth.entity.UserLinkUser;
import com.itrip.itripauth.mapper.HotelOrderMapper;
import com.itrip.itripauth.mapper.HotelTempStoreMapper;
import com.itrip.itripauth.service.HotelOrderService;
import com.itrip.itripauth.vo.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 四阶段项目二组
 * @since 2020-02-25
 */
@Service
public class HotelOrderServiceImpl extends ServiceImpl<HotelOrderMapper, HotelOrder> implements HotelOrderService {

    @Resource
    private HotelOrderMapper hotelOrderMapper;
    @Resource
    private HotelTempStoreMapper hotelTempStoreMapper;

    @Override
    public PageVo<HotelOrder> getPersonalOrderList(HotelOrderVo hotelOrderVo) {
        //获取总记录数
        Integer count = hotelOrderMapper.getPersonalOrderInfoCount(hotelOrderVo);
        if (hotelOrderVo.getPageNo() == null) {
            hotelOrderVo.setPageNo(0);
        }
        Integer pageNo = hotelOrderVo.getPageNo();
        Integer pageSize = hotelOrderVo.getPageSize();
        PageVo pageVo = new PageVo(pageNo, pageSize, count);
        pageVo.setRows(hotelOrderMapper.getPersonalOrderList(hotelOrderVo));
        return pageVo;
    }


    @Override
    public HotelOrder getHotelOrderById(String orderId) {
        return hotelOrderMapper.selectById(orderId);
    }

    @Override
    public PersonalOrderRoomVO getHotelOrderRoomInfoById(Long orderId) throws Exception {
        return baseMapper.getHotelOrderRoomInfoById(orderId);
    }

    @Override
    public HotelOrder getHotelOrderById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * @param orderNo 订单号
     * @return
     */
    @Override
    public HotelOrder loadHotelOrder(String orderNo) throws Exception {
        QueryWrapper<HotelOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        HotelOrder hotelOrder = hotelOrderMapper.selectOne(queryWrapper);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        //判断当前时间是否超过退房时间
        //当前系统时间

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 把日期对象转成指定格式的字符串 format
        String theCurrentTime = dateFormat.format(new Date());
        System.out.println(theCurrentTime);
        //退房时间
        String checkOutDate = dateFormat.format(hotelOrder.getCheckOutDate());
        System.out.println(checkOutDate);
        Integer i = checkOutDate.compareTo(theCurrentTime);
        //Integer i = theCurrentTime.compareTo(checkOutDate);
        if (i != -1)
            return hotelOrder;
        else
            return null;

    }

    @Override
    public Map<String, String> updateOrder(AddOrderVo addOrderVo) {
        StringBuffer sb = new StringBuffer();
        for (UserLinkUser items : addOrderVo.getLinkUser()) {
            sb.append(items.getLinkUserName() + ",");
        }
        //入住人
        addOrderVo.setLinkUserName(sb.toString());
        //入住天数
        int days = (int) ((addOrderVo.getCheckOutDate().getTime() - addOrderVo.getCheckInDate().getTime()) / (1000 * 3600 * 24));
        addOrderVo.setBookingDays(days);
        //订单金额
        RoomStoreVO roomStoreVO = hotelTempStoreMapper.getPreorderInfo(addOrderVo);
        Integer price = roomStoreVO.getPrice() * addOrderVo.getCount() * days;
        addOrderVo.setPayAmount(price);
        int count = hotelOrderMapper.updateHotelOrder(addOrderVo);
        if (count > 0) {
            HotelOrder hotelOrder = baseMapper.selectById(addOrderVo.getId());
            Map<String, String> map = new HashMap<>();
            map.put("id", hotelOrder.getId().toString());
            map.put("orderNo", hotelOrder.getOrderNo());
            return map;
        }
        return null;

    }

    @Override
    public Map<String, Object> getHotelOrderRoomId(Integer hotelId, Integer orederId) {
        HotelOrder hotelOrderRommId = hotelOrderMapper.getHotelOrderRoomId(hotelId, orederId);
        Map<String, Object> map = new HashMap<>();
        map.put("roomId", hotelOrderRommId.getRoomId());
        return map;
    }

    @Override
    public Map<String, String> addHotelOrder(AddOrderVo addOrderVo) {
        StringBuffer sb = new StringBuffer();
        for (UserLinkUser items : addOrderVo.getLinkUser()) {
            sb.append(items.getLinkUserName() + ",");
        }
        //入住人
        addOrderVo.setLinkUserName(sb.toString());
        //生成订单号：机器码 +日期+（MD5）（商品IDs+毫秒数+1000000的随机数）
        StringBuilder md5String = new StringBuilder();
        md5String.append(addOrderVo.getHotelId());
        md5String.append(addOrderVo.getRoomId());
        md5String.append(System.currentTimeMillis());
        md5String.append(Math.random() * 1000000);
        String md5 = MD5.getMd5(md5String.toString(), 6);
        //生成订单编号
        StringBuilder orderNo = new StringBuilder();
        orderNo.append("D1000001");
        try {
            orderNo.append(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        orderNo.append(md5);
        //订单号
        addOrderVo.setOrderNo(orderNo.toString());
        //订单状态
        addOrderVo.setOrderStatus(0);
        int days = (int) ((addOrderVo.getCheckOutDate().getTime() - addOrderVo.getCheckInDate().getTime()) / (1000 * 3600 * 24));
        //入住天数
        addOrderVo.setBookingDays(days);
        //创建时间
        Date nowDate = new Date();
        addOrderVo.setCreationDate(nowDate);
        //订单金额
        RoomStoreVO roomStoreVO = hotelTempStoreMapper.getPreorderInfo(addOrderVo);
        Integer price = roomStoreVO.getPrice() * addOrderVo.getCount() * days;
        addOrderVo.setPayAmount(price);
        if (hotelOrderMapper.addHotelOrder(addOrderVo) > 0) {
            //新增订单成功
            HotelTempStore hotelTempStore = new HotelTempStore();
            hotelTempStore.setHotelId(addOrderVo.getHotelId());
            hotelTempStore.setRoomId(addOrderVo.getRoomId());
            //当前时间
            Date date = new Date();
            hotelTempStore.setCreationDate(date);
            hotelTempStore.setRecordDate(date);
            //预定后的库存数
            Integer roomCount = hotelTempStoreMapper.getRoomCount(addOrderVo);
            hotelTempStore.setStore(roomCount - addOrderVo.getCount());
            int tempCount = hotelTempStoreMapper.addTempStore(hotelTempStore);
            if (tempCount > 0) {
                //更新库存成功
                HotelOrder hotelOrder = hotelOrderMapper.loadHotelOrder(orderNo.toString());
                Map<String, String> map = new HashMap<>();
                map.put("id", hotelOrder.getId().toString());
                map.put("orderNo", hotelOrder.getOrderNo());
                return map;
            }
        }
        return null;
    }

    @Override
    public Integer updateHotelOrder(HotelOrder hotelOrder) {
        return baseMapper.updateById(hotelOrder);
    }

    @Override
    public int timedCancellation() {
        //1.查询出预定时间超过两个小时的数据并保存起来
        List<HotelOrder> hotelOrderList = baseMapper.getHotelOrderList();
        if (hotelOrderList!=null && hotelOrderList.size()>0) {
            try {
                //2.根据超过两个小时的数据循环的修改订单状态
                for (HotelOrder hotel : hotelOrderList) {
                    //根据id循环修改订单状态
                    baseMapper.cycleChangesHotelOrder(hotel.getId());
                    //3.判断实时库存表的预定时间和超过两个小时的的预定，进行比较然后删除库存记录
                    //获取当前时间和实时库存表进行匹配，然后循环删除库存记录(增加库存)
                    hotelTempStoreMapper.deleteHotelOrder(hotel.getCreationDate());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("取消订单成功");
            return 1;
        }
        return 2;
    }
}
